package com.tc.report.intersect;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.tc.report.DnCell;
import com.tc.report.ReportAreaHandle;
import com.tc.report.ReportField;
import com.tc.report.ReportValueNote;
import com.tc.report.StringUtils;

public class ValAreaHandle extends ReportAreaHandle {
	public ValAreaHandle(){
		super();
	}
	public ValAreaHandle(IntersectReportImpl reportManage){
		super(reportManage);
	}
	@Override
	public int getMaxColSpan() {
		// TODO Auto-generated method stub
		return 0;
	}
	@Override
	public int getMaxRowSpan() {
		// TODO Auto-generated method stub
		return 0;
	}
	/**
	 * 处理值区域的数据。
	 */
	@Override
	public List<List<DnCell>> dealAreaDataValue(List<List<DnCell>> resultList) throws Exception {
		IntersectReportImpl reportManage = this.getReportManage();
		ReportAreaHandle rowAreaHandle = reportManage.getRowAreaHandle();
		if(rowAreaHandle!=null){
			int startRow = reportManage.getSpanRowOfRowTileCell();
			List<ReportValueNote> rowRootNote = rowAreaHandle.getRootNoteList();
			int multiple = reportManage.getMultipleOfValArea(reportManage.isRowFieldOfValue());
			//递归处理一级节点。
			for(ReportValueNote curNode:rowRootNote){
				startRow=this.dealRowAreaData(resultList, curNode, startRow);
				startRow +=multiple;
			}
			//处理行区域合计值。
			if(reportManage.isShowRowTotal()){//行区域合计值。
				this.dealRowTotalData(resultList);
			}
		}else{//如果只有列区域。TODO
			
		}
		return resultList;
	}
	
	/**
	 * 处理行区域的总计行.
	 * @param rowDataList
	 * @throws Exception
	 */
	private void dealRowTotalData(List<List<DnCell>> rowDataList) throws Exception{
		IntersectReportImpl reportManage = this.getReportManage();
		int multiple = reportManage.getMultipleOfValArea(reportManage.isRowFieldOfValue());
		List<DnCell> rowData = new ArrayList<DnCell>();
		if(rowDataList.size()==0){
			if(multiple==1){
				DnCell curCell = new DnCell();//跨行和跨列都为1.
				curCell.setFieldValue("汇总");
				rowData.add(curCell);
				rowDataList.add(rowData);
			}else{
				ReportAreaHandle valAreaHandle = reportManage.getValAreaHandle();
				ReportField rootField = valAreaHandle.getRootField();
				DnCell curCell = new DnCell();//跨行和跨列都为1.
				curCell.setFieldValue(rootField.getValFieldAlias());
				rowData.add(curCell);
				rowDataList.add(rowData);
				String nextFieldName = rootField.getNextFieldName();
				while(!"".equals(nextFieldName)){
					curCell = new DnCell();//跨行和跨列都为1.
					rowData = new ArrayList<DnCell>();
					ReportField reportField = valAreaHandle.getReportField(nextFieldName);
					curCell.setFieldValue(reportField.getValFieldAlias());
					rowData.add(curCell);
					rowDataList.add(rowData);
				}
			}
		}
		int curRowNum = rowDataList.size()-multiple;//当前行数.
		curRowNum = this.dealColAreaData(rowDataList, curRowNum, null);
	}
	
	/**
	 * 
	 * @param rowDataList  二维结果集.
	 * @param curNode      当前处理节点对象.
	 * @param titleRowNum  标题行数.
	 * @param startRow     当前节点的起始处理行.
	 * @param spanOfCurNode 当前节点的跨行数.
	 * @throws Exception
	 */
	private int dealRowAreaData(List<List<DnCell>> rowDataList,ReportValueNote curNode,int startRow)throws Exception{
		IntersectReportImpl reportManage = this.getReportManage();
		int curRowNum = startRow;//当前行数.
		if(curRowNum>rowDataList.size()){
			throw new Exception("值区域未初始化行结果集.");
		}
		
		//当前行区域的是否存在多个值区域字段。
		int multiple = reportManage.getMultipleOfValArea(reportManage.isRowFieldOfValue());
		List<ReportValueNote> sonList = curNode.getSonList();
		/**
		 * 如果是最后一个字段。
		 */
		if(sonList.size()==0){
			//递归到最一个字段
			curRowNum = this.dealColAreaData(rowDataList, curRowNum, curNode);
		}else{
			//再递归处理子节点信息.
			for(ReportValueNote sonNode:sonList){
				curRowNum = this.dealRowAreaData(rowDataList, sonNode,curRowNum);
				curRowNum +=multiple;//设置下一个子节点的起始行.
			}
		}
		//处理当前节点的合计值节点
		if(curNode.isShowTotalCell()){//处理合计行的值.
			curRowNum = this.dealColAreaData(rowDataList, curRowNum, curNode);
		}
		return curRowNum;
	}
	/**
	 * 针对某个行，处理列区域的数据。
	 * @param rowDataList
	 * @param curRowNum
	 * @param curNodeResultList
	 * @return
	 * @throws Exception
	 */
	private int dealColAreaData(List<List<DnCell>> rowDataList, int curRowNum, ReportValueNote curRowNode) throws Exception {
		IntersectReportImpl reportManage = this.getReportManage();
		ReportAreaHandle colAreaHandle = reportManage.getColAreaHandle();
		if (colAreaHandle == null) {
			//List<DnCell> rowData = rowDataList.get(curRowNum);
			curRowNum = this.dealValAreaData(rowDataList, curRowNum, curRowNode);
		} else {//如果存在列区域。
			List<ReportValueNote> colRootNoteList = colAreaHandle.getRootNoteList();// 列区域的一级值列表.
			/**
			 * 处理列区域每个节点的数据。
			 */
			for (ReportValueNote curColNode : colRootNoteList) {
				curRowNum = this.filterColAreaData(rowDataList, curRowNode, curColNode, curRowNum);
			}
			/**
			 * 处理列区域总计节点的数据。
			 */
			if (reportManage.isShowColTotal()) {//列区域总计值。
				//List<DnCell> rowData = rowDataList.get(curRowNum);
				curRowNum = this.dealValAreaData(rowDataList, curRowNum, curRowNode);
			}
		}
		return curRowNum;
	}
	
	/**
	 * 处理列区域的数据。
	 * @param rowDataList
	 * @param resultNode  存储符合当前节点查询结果集的节点对象。
	 * @param curColNode
	 * @param startRow
	 * @throws Exception
	 */
	public int filterColAreaData(List<List<DnCell>> rowDataList,ReportValueNote resultNode, ReportValueNote curColNode,int startRow) throws Exception {
		/**
		 * 将当前行节点的行结果集利用当前列字段再次进行过滤。
		 */
		this.filterResultList(resultNode, curColNode);
		/**
		 * 递归处理子节点下的数据。
		 */
		List<ReportValueNote> colSonList = curColNode.getSonList();
		/**
		 * 如果是最后一个字段。
		 */
		if(colSonList.size()==0){
			startRow = this.dealValAreaData(rowDataList, startRow, curColNode);
		}else{
			for(ReportValueNote sonNode:colSonList){
				/**
				 * resultNode 需要使用父节点的查询结果集作为子节点的查询结果集。
				 */
				startRow = filterColAreaData(rowDataList,curColNode,sonNode,startRow);
			}
		}
		//处理当前节点的合计值节点
		if(curColNode.isShowTotalCell()){//处理合计行的值.
			startRow = this.dealValAreaData(rowDataList, startRow, curColNode);
		}
		
		return startRow;
	}
	
	/**
	 * 获取当前节点的行结果集。如果curRowNode为空，则为总计节点
	 * @param curNode
	 * @param type :1-原始查询结果集，2－字典转换后的查询结果集。
	 * @return
	 */
	private List<Map<String, Object>> findCurRowQueryResultList(ReportValueNote curNode,String type){
		IntersectReportImpl reportManage = this.getReportManage();
		List<Map<String, Object>> curNodeResultList=null;
		if(curNode==null){//处理行的总计。
			curNodeResultList = reportManage.getQueryResult();
		}else{
			if("1".equals(type)){
				curNodeResultList = curNode.getQueryResultList();//当前节点的所包含的结果集.
			}else{
				curNodeResultList = curNode.getResultList();
			}
		}
		return curNodeResultList;
	}
	/**
	 * 处理当前交叉节点上的值区域的数据。
	 * @param rowDataList
	 * @param curRowNum
	 * @param rowData
	 * @param paraNode
	 * @throws Exception
	 */
	private int dealValAreaData(List<List<DnCell>> rowDataList, int curRowNum, ReportValueNote paraNode) throws Exception {
		IntersectReportImpl reportManage = this.getReportManage();
		ReportAreaHandle valAreaHandle = reportManage.getValAreaHandle();
		ReportField valRootField = valAreaHandle.getRootField();
		boolean isRowFieldOfValue = reportManage.isRowFieldOfValue();//存在多个值字段时是否显示在行区域中.
		String nextFieldName ="";
		int startRow = curRowNum;
		List<DnCell> rowData = rowDataList.get(startRow);//当前行结果集。
		nextFieldName = calcValAreaData(rowData,paraNode,valRootField);
		
		while(!"".equals(nextFieldName)){//如果有后续节点.
			if(isRowFieldOfValue){//显示在行区域中.
				startRow++;
				rowData = rowDataList.get(startRow);
			}
			ReportField nextReportField = this.getReportField(nextFieldName);
			nextFieldName = calcValAreaData(rowData,paraNode,nextReportField);
		}
		return curRowNum;
	}
	/**
	 * 计算值区域的数据.
	 * @param rowData
	 * @param resultList  符合当前交叉数据的结果集.
	 * @param valField
	 */
	public String calcValAreaData(List<DnCell> rowData,ReportValueNote resultNode,ReportField valField) throws Exception{
		if(rowData==null||rowData.size()==0){
			throw new Exception("未计算行区域的结果集.");
		}
		List<Map<String, Object>> queryResultList = this.findCurRowQueryResultList(resultNode,"1");
		//List<Map<String, Object>> resultList = this.findCurRowQueryResultList(resultNode,"1");
		DnCell lastCell = rowData.get(rowData.size()-1);//获取当前行的最后一个单元节点.
		DnCell curCell = new DnCell();//跨行和跨列都为1.
		//curCell.setQueryResultList(queryResultList);//保存当前符合当前节点值的结果值。
		//curCell.setResultList(resultList);//保存当前符合当前节点值的结果值。
		int posX = lastCell.getPosX()+lastCell.getSpancol();//
		int posY = lastCell.getPosY();//同行,Y轴坐标一致.
		curCell.setPosX(posX);
		curCell.setPosY(posY);
		String fieldName = valField.getFieldName();
		String totalValType = valField.getTotalValType();//获取值区域字段的汇总方式.
		String cellValue = "";
		IntersectReportImpl reportManage = this.getReportManage();
		if(queryResultList.size()==0){//如果是空结果集.
			boolean isShowBlankValue = reportManage.isShowBlankValue();
			if(isShowBlankValue){
				cellValue = reportManage.getShowBlankValue();//设置空白值的显示值.
			}
		}else{
			if (ReportField.TOTAL_TYPE_CNT.equals(totalValType)) {// 如果是计数方式
				cellValue = String.valueOf(queryResultList.size());
			} else {
				BigDecimal bValule = new BigDecimal(0);
				boolean isError = false;
				for (Map<String, Object> result : queryResultList) {
					String fieldValue = StringUtils.objToString(result.get(fieldName));
					try {
						bValule = bValule.add(new BigDecimal(fieldValue));
					} catch (Exception e) {
						isError  = true;
						break;
					}
				}
				if(isError){//判断是否出错。
					cellValue ="";
					boolean showErrorValue = reportManage.isShowErrorValue();
					if(showErrorValue){
						cellValue=reportManage.getShowErrorValue();
					}
				}else{
					cellValue = String.valueOf(bValule);
					if (ReportField.TOTAL_TYPE_SUM.equals(totalValType)) {//求和值.
						if(!"".equals(cellValue)&&!reportManage.getShowErrorValue().equals(cellValue)){
							cellValue = String.valueOf(bValule);
						}
					} else if (ReportField.TOTAL_TYPE_AVG.equals(totalValType)) {//平均值.
						if(!"".equals(cellValue)&&!reportManage.getShowErrorValue().equals(cellValue)){
							cellValue = String.valueOf(bValule.divide(new BigDecimal(queryResultList.size())));
						}
					}
				}
			}
		}
		curCell.setFieldValue(cellValue);
		rowData.add(curCell);
		String nextFieldName = valField.getNextFieldName();
		return nextFieldName;
	}
	
	
	/**
	 * 过滤结果集.
	 * @param pareNode   父级结果集节点信息。
	 * @param curColNode
	 * @return
	 */
	private void filterResultList(ReportValueNote pareNode, ReportValueNote curColNode) {
		/**
		 * 设置当前列节点结果集前，需要将原来的结果集初始化。
		 */
		curColNode.initNodeResultList();//
		String fieldName = curColNode.getFieldName();//当前节点所在字段名称.
		String code = curColNode.getCode();//当前节点的值.
		List<Map<String, Object>> resultList = findCurRowQueryResultList(pareNode,"1");
		for(Map<String, Object> result:resultList){
			String fieldValue = StringUtils.objToString(result.get(fieldName));
			if(Objects.equals(code,fieldValue)){
				curColNode.addQueryResult(result);
			}
		}
		/**
		 * 处理字典名称转换。
		 */
		ReportAreaHandle areaHandle = curColNode.getAreaHandle();
		ReportField reportField = areaHandle.getReportField(fieldName);
		resultList = findCurRowQueryResultList(pareNode,"2");
		Map<String, Object> fieldDict = reportField.getFieldDict();
		for(Map<String, Object> result:resultList){
			String fieldValue = StringUtils.objToString(result.get(fieldName));
			if(Objects.equals(code,fieldValue)|| Objects.equals(fieldValue,fieldDict.get(code))){
				String dictName = fieldDict.get(fieldValue)==null?fieldValue:(String)fieldDict.get(fieldValue);
				result.put(fieldName,dictName);
				curColNode.getResultList().add(result);
			}
		}
	}
	
	
}
